import instance from "./axios"

const post = (url, data) => {
    return new Promise((resolve, reject) => {
        instance.post(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
const get = (url, data) => {
    return new Promise((resolve, reject) => {
        instance.get(url, { params: data }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
const put = (url, data) => {
    return new Promise((resolve, reject) => {
        instance.put(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

const del = (url, data) => {
    return new Promise((resolve, reject) => {
        instance.delete(url, { params: data }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}
const downloadFile = (url, data) => {
    return new Promise((resolve, reject) => {
        instance.get(url,{ responseType: "blob",data}).then(res=>{
            console.log(res)
            const str = res.headers['content-disposition']
            if (!res || !str) {
                console.log('下载失败！')
                return
            }
            if (res && res.status === 200 && res.data) {
                const link = document.createElement("a");
                // 创建Blob对象, 固定写法
                let blob = new Blob([res.data]);
                // 设置元素样式不可⻅
                link.style.display = "none";
                // 创建下载链接
                link.href = URL.createObjectURL(blob);
                let contentDisposition = res.headers["content-disposition"];
                // 获取⽂件名(后端应确保正确返回⽂件名)
                const fileName = window.decodeURI(
                    contentDisposition.substring(contentDisposition.indexOf("=") + 1)
                );
                link.setAttribute("download", fileName);
                // 加⼊dom树
                document.body.appendChild(link);
                // ⼿动触发点击事件
                link.click();
                // 移除之前创建的元素
                document.body.removeChild(link);
                // 释放Blob对象
                window.URL.revokeObjectURL(link.href);
            }
            }).catch(err => {
            reject(err);
        })
    });
}



export default {
    post, get, put, del,downloadFile
}